<template>
    <div class="search-page">
        <!-- 导航栏 -->
        <van-nav-bar title="商品搜索" left-arrow @click-left="goBack" />

        <!-- 搜索框区域 -->
        <div class="search-container">
            <div class="search-box">
                <van-search v-model="searchValue" placeholder="请输入商品名称搜索" @search="handleSearch" @clear="handleClear"
                    show-action action-text="取消" @click-action="handleCancel" autocomplete="off" />
            </div>

            <!-- 热门推荐标签 -->
            <div class="hot-tags" v-if="!isSearching">
                <p class="tag-title">热门推荐</p>
                <div class="tags">
                    <span v-for="(product, index) in hotProducts" :key="product.id"
                        @click="handleHotProductClick(product)" :class="{ 'first-hot-product': index === 0 }" 
                        >
                        {{ product.name }}
                    </span>
                </div>
            </div>

            <!-- 搜索建议（搜索后显示） -->
            <div class="search-suggestions" v-if="isSearching && suggestions.length > 0">
                <p class="suggest-title">搜索建议</p>
                <div class="suggest-list">
                    <div v-for="item in suggestions" :key="item" @click="handleSuggestClick(item)">
                        {{ item }}
                    </div>
                </div>
            </div>

            <!-- 搜索状态提示 -->
            <div v-if="isSearching" class="search-status">
                <p v-if="searchLoading">搜索中...</p>
                <p v-else-if="products.length === 0 && searchValue">未找到与"{{ searchValue }}"相关的商品</p>
            </div>

            <!-- 搜索结果列表 -->
            <div class="product-results" v-if="isSearching && products.length > 0">
                <van-grid :column-num="2" border="false">
                    <van-grid-item v-for="product in products" :key="product.id" @click="goToProductDetail(product.id)">
                        <div class="product-card">
                            <img :src="product.image_url" :alt="product.name" class="product-img" />
                            <div class="product-info">
                                <p class="product-name">{{ product.name }}</p>
                                <p class="product-price">¥{{ product.price.toFixed(2) }}</p>
                            </div>
                        </div>
                    </van-grid-item>
                </van-grid>
            </div>

            <!-- 错误提示 -->
            <div class="error-message" v-if="errorMessage">
                {{ errorMessage }}
                <van-button size="small" @click="handleSearch">重试</van-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import api from '@/api/history';

// 路由实例
const router = useRouter();

// 响应式数据
const searchValue = ref('');
const isSearching = ref(false); // 搜索状态标记
const searchLoading = ref(false); // 搜索加载状态
const products = ref([]); // 搜索结果商品列表
const errorMessage = ref(''); // 错误信息
const hotTags = ref([]); // 热门推荐标签
const suggestions = ref([]); // 搜索建议列表

// 返回上一页
const goBack = () => {
    router.back();
};

// 处理搜索建议点击
const handleSuggestClick = (suggest) => {
    searchValue.value = suggest;
    handleSearch();
};

// 搜索商品
const handleSearch = async () => {
    if (!searchValue.value.trim()) {
        showToast('请输入搜索关键词');
        return;
    }

    try {
        searchLoading.value = true;
        isSearching.value = true;

        // 生成搜索建议（实际项目可从接口获取）
        suggestions.value = hotTags.value.filter(item =>
            item.includes(searchValue.value.trim())
        );

        // 调用搜索API
        const response = await api.get('/products/search', {
            params: { keyword: searchValue.value.trim() }
        });
        products.value = response.data.products || [];

    } catch (error) {
        showToast('搜索失败，请重试');
        errorMessage.value = '搜索服务异常，请稍后再试';
        console.error('搜索商品失败:', error);
    } finally {
        searchLoading.value = false;
    }
};

// 清除搜索
const handleClear = () => {
    searchValue.value = '';
    isSearching.value = false;
    products.value = [];
    suggestions.value = [];
    errorMessage.value = '';
};

// 取消搜索
const handleCancel = () => {
    handleClear();
};

// 前往商品详情
const goToProductDetail = (productId) => {
    router.push({ name: 'ProductDetail', params: { id: productId } });
};

const hotProducts = ref([]); // 替换原来的hotTags

// 获取热门推荐商品
const fetchHotRecommendations = async () => {
    try {
        const response = await api.get('/products/hot_recommendations', {
            params: { limit: 8 } // 获取8个热门商品
        });
        hotProducts.value = response.data;
    } catch (error) {
        console.error('获取热门推荐失败:', error);
        // 失败时使用默认标签 fallback
        hotProducts.value = [
            { id: 1, name: '苹果奶绿' },
            { id: 2, name: '草莓啵啵' },
            // ... 其他默认标签
        ];
    }
};

// 处理热门商品点击
const handleHotProductClick = (product) => {
    searchValue.value = product.name;
    handleSearch();
};

// 初始化时获取热门推荐
onMounted(() => {
    fetchHotRecommendations();
});
</script>

<style scoped>
.search-page {
    background-color: #f5f5f7;
    min-height: 100vh;
}

.search-container {
    padding: 15px;
}

/* 搜索框样式 */
.search-box {
    margin-bottom: 20px;
}

.van-search {
    background-color: #fff;
    border-radius: 20px;
    padding: 0 10px;
}

.van-search__action {
    color: #666;
    font-size: 14px;
}

/* 第一个热门商品特殊样式 */
.tags span.first-hot-product {
    background-color: #f1b1bf;
    /* 橙色背景（示例） */
    color: rgb(230, 123, 123);
    /* 白色文字 */
    font-weight: bold;
    /* 加粗 */
    padding: 8px 16px;
    /* 稍大的内边距 */
    box-shadow: 0 2px 8px rgba(255, 107, 0, 0.3);
    /* 轻微阴影 */
}

/* 第一个热门商品点击效果 */
.tags span.first-hot-product:active {
    background-color: #e05a00;
    /* 点击时加深颜色 */
}

/* 热门标签样式 */
.hot-tags {
    background-color: #fff;
    border-radius: 10px;
    padding: 15px;
}

.tag-title {
    font-size: 14px;
    color: #999;
    margin-bottom: 10px;
}

.tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.tags span {
    background-color: #f5f5f7;
    color: #333;
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
    white-space: nowrap;
}

.tags span:active {
    background-color: #e8e8ea;
}

/* 搜索建议样式 */
.search-suggestions {
    background-color: #fff;
    border-radius: 10px;
    padding: 15px;
    margin-top: 10px;
}

.suggest-title {
    font-size: 14px;
    color: #999;
    margin-bottom: 10px;
}

.suggest-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.suggest-list div {
    font-size: 15px;
    padding: 8px 0;
    border-bottom: 1px solid #f5f5f5;
    cursor: pointer;
}

.suggest-list div:last-child {
    border-bottom: none;
}

/* 搜索状态提示 */
.search-status {
    text-align: center;
    padding: 30px 0;
    color: #666;
    font-size: 14px;
}

/* 商品结果样式 */
.product-results {
    margin-top: 15px;
}

.product-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fff;
    border-radius: 8px;
    padding: 10px;
    height: 100%;
}

.product-img {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 8px;
    margin-bottom: 10px;
}

.product-info {
    text-align: center;
    width: 100%;
}

.product-name {
    font-size: 14px;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 5px;
}

.product-price {
    font-size: 15px;
    color: #ff4d4f;
    font-weight: bold;
}

/* 错误提示样式 */
.error-message {
    text-align: center;
    padding: 20px;
    color: #ff4d4f;
    font-size: 14px;
}

/* 适配移动端 */
@media (max-width: 768px) {
    .search-container {
        padding: 10px;
    }

    .tags span {
        padding: 5px 12px;
        font-size: 13px;
    }
}
</style>